package com.xiaotu.memcached.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.internal.OperationFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.SocketAddress;
import java.util.*;

/**
 * @author zhangxiao
 * @create 2022-04-07 14:29
 */
@RestController
public class MemcacheController {

    @Autowired
    private MemcachedClient memcachedClient;

    @GetMapping("/memcache")
    public String memcache() throws InterruptedException {
        final Map<SocketAddress, Map<String, String>> stats = memcachedClient.getStats();
        System.out.println(stats);
        // 放入缓存, 如下参数key为name，值为louis，过期时间为5，单位为秒
        OperationFuture<Boolean> flag = memcachedClient.set("name", 5, "louis");
        // 取出缓存
        Object value = memcachedClient.get("name");
        System.out.println(value);
        // 多线程睡眠5秒,让
        Thread.sleep(7000);
        value = memcachedClient.get("name");
        System.out.println(value);
        return "success";
    }

    /**
     * 模拟加入房间
     *
     * @return
     */
    @GetMapping("/addRoom")
    public String addRoom(String roomId, Integer userId) {
        if (ObjectUtil.isNull(memcachedClient.get(roomId))) {
            List<Integer> list = new ArrayList<>();
            list.add(userId);
            memcachedClient.set(roomId, 0, list);
        } else {
            List<Integer> list = (List<Integer>) memcachedClient.get(roomId);
            list.add(userId);
            memcachedClient.replace(roomId, 0, list);
        }
        return "success";
    }

    /**
     * 模拟离开房间
     *
     * @return
     */
    @GetMapping("/leaveRoom")
    public String leaveRoom(String roomId, Integer userId) {
        List<Integer> list = (List<Integer>) memcachedClient.get(roomId);
        list.remove(userId);
        if (CollectionUtil.isNotEmpty(list)) {
            memcachedClient.replace(roomId, 0, list);
        } else {
            memcachedClient.delete(roomId);
        }
        return "success";
    }

    /**
     * 模拟获取对方用户ID
     *
     * @return
     */
    @GetMapping("/anotherUserId")
    public Object anotherUserSession(String roomId, Integer userId) {
        List<Integer> list = (List<Integer>) memcachedClient.get(roomId);
        if (CollectionUtil.isNotEmpty(list) && list.size() == 2)
            return list.stream().filter(l -> !l.equals(userId)).findFirst().get();
        return null;
    }

}
